package com.ly.system.controller;

import com.ass.sse.constant.ResultCode;
import com.ass.sse.service.SseService;
import com.ass.sse.vo.MessageVo;
import com.common.core.domain.AjaxResult;
import com.common.core.web.controller.BaseController;
import org.apache.http.HttpResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;


/**
 * SSE 控制器
 *
 * @author zwd
 * @version 1.0
 * @since 2025-01-15 15:18
 */
@RestController
@RequestMapping("/sse")
public class SseController extends BaseController {
    @Resource
    private SseService sseService;

    /**
     * 创建SseEmitter链接
     *
     * @param userId 用户id
     * @return SseEmitter实例
     * produces = MediaType.TEXT_EVENT_STREAM_VALUE
     */
    @GetMapping(value = "/connect")
    public SseEmitter connect(@RequestParam String userId, HttpServletResponse response) {
        // 响应头设置
		response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
		response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
		response.setHeader(HttpHeaders.CONTENT_TYPE, "text/event-stream");
		response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
		response.setHeader(HttpHeaders.CONNECTION, "keep-alive");

        return sseService.connect(userId);
    }


    /**
     * 清理SseEmitter链接
     *
     * @param clientId 客户端ID
     * @return SseEmitter实例
     */
    @PostMapping(value = "/deleteSse/{clientId}")
    public AjaxResult deleteSse(@PathVariable String clientId) {
        try {
            sseService.deleteSseEmitter(clientId);
            return AjaxResult.success("清理成功：" + clientId);
        } catch (Exception e) {
            return AjaxResult.error("清理失败：" + e.getMessage());
        }
    }


    /**
     * 发送消息
     *
     * @return SseEmitter实例
     */
    @PostMapping(value = "/sendMessage")
    public AjaxResult sendMessage(@RequestBody MessageVo messageVo) {
        sseService.sendEvent(messageVo.getClientId(), messageVo);
        return AjaxResult.success(ResultCode.SUCCESS.getMessage());
    }
}
